package com.telit.common.entity;

import com.telit.common.enums.ResultCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;


@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "DataReturn", description = "返回结果")
public class DataReturn<T> implements Serializable {

    @ApiModelProperty(value = "返回码，请求成功：00000", required = true)
    private String code;

    @ApiModelProperty(value = "返回描述")
    private String errorMsg;

    @ApiModelProperty(value = "返回数据")
    private T data;

    public static <T> DataReturn<T> ok() {
        return new DataReturn(ResultCode.SUCCESS, "成功");
    }

    public static <T> DataReturn<T> ok(T o) {
        return new DataReturn<>(ResultCode.SUCCESS, o);
    }

    public static <T> DataReturn<T> ok(String message, T o) {
        return new DataReturn<>(ResultCode.SUCCESS, message, o);
    }

    public static <T> DataReturn<T> failure() {
        return new DataReturn(ResultCode.SERVER_ERROR, "失败");
    }

    public static <T> DataReturn<T> failure(String code, String msg) {
        return new DataReturn<>(code, msg);
    }

    public static <T> DataReturn<T> failure(ResultCode code) {
        return new DataReturn(code, "失败");
    }

    public static <T> DataReturn<T> failure(ResultCode code, T o) {
        return new DataReturn<>(code, o);
    }

    public DataReturn(ResultCode resultCode) {
        setResultCode(resultCode);
    }

    public DataReturn(ResultCode resultCode, T data) {
        setResultCode(resultCode);
        this.data = data;
    }

    public void setResultCode(ResultCode resultCode) {
        this.code = resultCode.getCode();
        this.errorMsg = resultCode.getMsg();
    }

    public DataReturn(ResultCode resultCode, String desc, T data) {
        setResultCode(resultCode);
        this.errorMsg = desc;
        this.data = data;
    }

    public DataReturn(String code,String msg){
        this.code = code;
        this.errorMsg = msg;
    }

    @Override
    public String toString() {
        return "{" +
                "\"code\":" + code +
                ", \"errorMsg\":\"" + errorMsg + '\"' +
                ", \"data\":\"" + data + '\"' +
                '}';
    }

}
